package com.xiaoKe.zhonghzu.global.base;

/**
 * @ProjectName : xiaoke-pad-zhongzhu
 * @Author : Shijingna
 * @Time : 2024/8/1 13:44
 * @Description : 文件描述
 */
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class EqualWidthGridLayoutManager extends GridLayoutManager {

    private int spanCount; // 列数
    private int spacing = 0; // 列间距

    public EqualWidthGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
        this.spanCount = spanCount;
    }

    public EqualWidthGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
        super(context, spanCount, orientation, reverseLayout);
        this.spanCount = spanCount;
    }

    public void setSpacing(int spacing) {
        this.spacing = spacing;
    }

    @Override
    public void onLayoutChildren(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        if (getItemCount() == 0) return;

        int width = getWidth() - getPaddingLeft() - getPaddingRight();
        int totalSpace = width - (spacing * (spanCount - 1));
        int itemWidth = totalSpace / spanCount;

        int itemHeight = itemWidth; // 或者你可以设置为固定高度，依据你的需求
        int leftOffset = getPaddingLeft();
        int topOffset = getPaddingTop();

        // 重新布局所有项
        for (int i = 0; i < getItemCount(); i++) {
            int spanIndex = i % spanCount;
            int rowIndex = i / spanCount;

            View view = recycler.getViewForPosition(i);
            addView(view);
            measureChildWithMargins(view, 0, 0);
            layoutDecorated(view,
                    leftOffset + spanIndex * (itemWidth + spacing),
                    topOffset + rowIndex * (itemHeight + spacing),
                    leftOffset + (spanIndex + 1) * itemWidth + spanIndex * spacing,
                    topOffset + (rowIndex + 1) * itemHeight + rowIndex * spacing);
        }
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }
}
